<template>
  <div class="dashboard-container">
    <div class="header">
      <h1>德州农林害虫资源库数据分析</h1>
      <div class="time-selector">
        <el-select class="input" v-model="timeRange" placeholder="请选择时间范围" @change="load">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>

    <!-- 害虫数量趋势分析 -->
    <el-card class="chart-card" shadow="hover">
      <div id="line" class="chart"></div>
    </el-card>

    <div class="chart-group">
      <!-- 害虫种类分布 -->
      <el-card class="chart-card" shadow="hover">
        <div id="pie" class="chart"></div>
      </el-card>

      <!-- 害虫区域分布 -->
      <el-card class="chart-card" shadow="hover">
        <div id="bar" class="chart"></div>
      </el-card>
    </div>

    <!-- 害虫防治效果 -->
    <el-card class="chart-card" shadow="hover">
      <div id="effect" class="chart"></div>
    </el-card>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import request from "@/utils/request";
import * as echarts from 'echarts'

// 农业主题颜色
const themeColors = [
  '#4CAF50', // 绿色
  '#8BC34A', // 浅绿
  '#CDDC39', // 黄绿
  '#FFC107', // 琥珀
  '#FF9800', // 橙色
  '#607D8B'  // 蓝灰
]

const lineOption = {
  title: {
    text: '害虫数量趋势分析',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 18,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['发现害虫数量', '防治处理数量'],
    right: 20,
    top: 10,
    textStyle: {
      color: '#666'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {
        title: '保存图片',
        pixelRatio: 2
      },
      dataZoom: {
        title: {
          zoom: '区域缩放',
          back: '缩放还原'
        }
      },
      magicType: {
        title: {
          line: '切换为折线图',
          bar: '切换为柱状图'
        },
        type: ['line', 'bar']
      }
    },
    right: 30,
    top: 10
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666'
    }
  },
  yAxis: {
    type: 'value',
    name: '数量(只)',
    nameTextStyle: {
      color: '#666'
    },
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666'
    },
    splitLine: {
      lineStyle: {
        color: '#eee'
      }
    }
  },
  series: [
    {
      name: '发现害虫数量',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 3,
        color: themeColors[0]
      },
      itemStyle: {
        color: themeColors[0]
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(76, 175, 80, 0.3)'
          },
          {
            offset: 1,
            color: 'rgba(76, 175, 80, 0.1)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      animationDelay: function (idx) {
        return idx * 100;
      },
      data: []
    },
    {
      name: '防治处理数量',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 3,
        color: themeColors[3]
      },
      itemStyle: {
        color: themeColors[3]
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(255, 193, 7, 0.3)'
          },
          {
            offset: 1,
            color: 'rgba(255, 193, 7, 0.1)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      animationDelay: function (idx) {
        return idx * 100 + 100;
      },
      data: []
    }
  ],
  animationEasing: 'elasticOut',
  animationDelayUpdate: function (idx) {
    return idx * 5;
  }
};

const pieOption = {
  title: {
    text: '害虫种类分布',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 18,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: [],
    textStyle: {
      color: '#666'
    }
  },
  series: [
    {
      name: '害虫种类',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold',
          formatter: '{b}\n{c} ({d}%)'
        }
      },
      labelLine: {
        show: false
      },
      data: [],
      animationType: 'scale',
      animationEasing: 'elasticOut',
      animationDelay: function (idx) {
        return Math.random() * 200;
      }
    }
  ]
};

const barOption = {
  title: {
    text: '害虫区域分布',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 18,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    name: '数量(只)',
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666'
    },
    splitLine: {
      lineStyle: {
        color: '#eee'
      }
    }
  },
  yAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666'
    }
  },
  series: [
    {
      name: '害虫数量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: function (params) {
          return themeColors[params.dataIndex % themeColors.length];
        },
        borderRadius: [0, 5, 5, 0]
      },
      label: {
        show: true,
        position: 'right'
      },
      animationDelay: function (idx) {
        return idx * 100;
      }
    }
  ],
  animationEasing: 'elasticOut'
};

const effectOption = {
  title: {
    text: '防治效果分析',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 18,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['防治前数量', '防治后数量', '防治效果'],
    right: 20,
    top: 10,
    textStyle: {
      color: '#666'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: [],
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '害虫数量(只)',
      position: 'left',
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    {
      type: 'value',
      name: '防治效果(%)',
      position: 'right',
      min: 0,
      max: 100,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666',
        formatter: '{value}%'
      },
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '防治前数量',
      type: 'line',
      smooth: true,
      lineStyle: {
        width: 3,
        color: themeColors[0]
      },
      itemStyle: {
        color: themeColors[0]
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(76, 175, 80, 0.3)'
          },
          {
            offset: 1,
            color: 'rgba(76, 175, 80, 0.1)'
          }
        ])
      },
      data: []
    },
    {
      name: '防治后数量',
      type: 'line',
      smooth: true,
      lineStyle: {
        width: 3,
        color: themeColors[3]
      },
      itemStyle: {
        color: themeColors[3]
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(255, 193, 7, 0.3)'
          },
          {
            offset: 1,
            color: 'rgba(255, 193, 7, 0.1)'
          }
        ])
      },
      data: []
    },
    {
      name: '防治效果',
      type: 'line',
      yAxisIndex: 1,
      smooth: true,
      lineStyle: {
        width: 3,
        color: themeColors[5]
      },
      itemStyle: {
        color: themeColors[5]
      },
      symbol: 'circle',
      symbolSize: 8,
      data: []
    }
  ]
};

export default {
  data() {
    return {
      admin: Cookies.get('admin') ? JSON.parse(Cookies.get('admin')) : {},
      lineChart: null,
      pieChart: null,
      barChart: null,
      effectChart: null,
      timeRange: 'week',
      options: [
        { label: '最近一周', value: 'week' },
        { label: '最近一个月', value: 'month' },
        { label: '最近两个月', value: 'month2' },
        { label: '最近三个月', value: 'month3' },
      ]
    }
  },
  mounted() {
    this.initCharts();
    this.load();

    // 窗口大小改变时重新调整图表大小
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
  },
  methods: {
    initCharts() {
      this.lineChart = echarts.init(document.getElementById('line'), 'custom');
      this.pieChart = echarts.init(document.getElementById('pie'), 'custom');
      this.barChart = echarts.init(document.getElementById('bar'), 'custom');
      this.effectChart = echarts.init(document.getElementById('effect'), 'custom');

      // 注册主题
      echarts.registerTheme('custom', {
        backgroundColor: '#f9f9f9',
        color: themeColors,
        title: {
          textStyle: {
            color: '#333'
          }
        },
        tooltip: {
          backgroundColor: 'rgba(255,255,255,0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          }
        }
      });
    },

    resizeCharts() {
      this.lineChart && this.lineChart.resize();
      this.pieChart && this.pieChart.resize();
      this.barChart && this.barChart.resize();
      this.effectChart && this.effectChart.resize();
    },

    load() {
      // 模拟数据请求
      this.loadLineData();
      this.loadPieData();
      this.loadBarData();
      this.loadEffectData();
    },

    loadLineData() {
      // 模拟API请求
      request.get('/pest/lineCharts/' + this.timeRange).then(res => {
        lineOption.xAxis.data = res.data.date;
        lineOption.series[0].data = res.data.found;
        lineOption.series[1].data = res.data.treated;
        this.lineChart.setOption(lineOption, true);
      }).catch(() => {
        // 模拟数据
        const dates = [];
        const now = new Date();
        const days = this.timeRange === 'week' ? 7 :
          this.timeRange === 'month' ? 30 :
            this.timeRange === 'month2' ? 60 : 90;

        for (let i = days; i >= 0; i--) {
          const date = new Date(now);
          date.setDate(date.getDate() - i);
          dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
        }

        const foundData = dates.map(() => Math.floor(Math.random() * 200) + 50);
        const treatedData = foundData.map(val => Math.floor(val * (0.7 + Math.random() * 0.2)));

        lineOption.xAxis.data = dates;
        lineOption.series[0].data = foundData;
        lineOption.series[1].data = treatedData;
        this.lineChart.setOption(lineOption, true);
      });
    },

    loadPieData() {
      request.get('/pest/pieCharts/' + this.timeRange).then(res => {
        pieOption.legend.data = res.data.categories.map(item => item.name);
        pieOption.series[0].data = res.data.categories;
        this.pieChart.setOption(pieOption, true);
      }).catch(() => {
        // 模拟数据
        const pests = [
          { value: 335, name: '棉铃虫' },
          { value: 310, name: '玉米螟' },
          { value: 234, name: '蚜虫' },
          { value: 135, name: '红蜘蛛' },
          { value: 154, name: '飞虱' },
          { value: 98, name: '其他' }
        ];

        pieOption.legend.data = pests.map(item => item.name);
        pieOption.series[0].data = pests;
        this.pieChart.setOption(pieOption, true);
      });
    },

    loadBarData() {
      request.get('/pest/barCharts/' + this.timeRange).then(res => {
        barOption.yAxis.data = res.data.areas;
        barOption.series[0].data = res.data.counts;
        this.barChart.setOption(barOption, true);
      }).catch(() => {
        // 模拟数据
        const areas = ['德城区', '陵城区', '禹城市', '乐陵市', '宁津县', '齐河县', '临邑县', '平原县', '武城县', '夏津县', '庆云县'];
        const counts = areas.map(() => Math.floor(Math.random() * 500) + 100);

        barOption.yAxis.data = areas;
        barOption.series[0].data = counts;
        this.barChart.setOption(barOption, true);
      });
    },

    loadEffectData() {
      request.get('/pest/effectCharts/' + this.timeRange).then(res => {
        effectOption.xAxis[0].data = res.data.dates;
        effectOption.series[0].data = res.data.before;
        effectOption.series[1].data = res.data.after;
        effectOption.series[2].data = res.data.effect;
        this.effectChart.setOption(effectOption, true);
      }).catch(() => {
        // 模拟数据
        const dates = [];
        const now = new Date();
        const days = this.timeRange === 'week' ? 7 :
          this.timeRange === 'month' ? 30 :
            this.timeRange === 'month2' ? 60 : 90;

        for (let i = days; i >= 0; i -= 7) {
          const date = new Date(now);
          date.setDate(date.getDate() - i);
          dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
        }

        const beforeData = dates.map(() => Math.floor(Math.random() * 200) + 50);
        const afterData = beforeData.map(val => Math.floor(val * (0.2 + Math.random() * 0.3)));
        const effectData = beforeData.map((val, idx) => Math.floor((1 - afterData[idx] / val) * 100));

        effectOption.xAxis[0].data = dates;
        effectOption.series[0].data = beforeData;
        effectOption.series[1].data = afterData;
        effectOption.series[2].data = effectData;
        this.effectChart.setOption(effectOption, true);
      });
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.header h1 {
  color: #4CAF50;
  font-size: 24px;
  margin: 0;
}

.time-selector {
  display: flex;
  align-items: center;
}

.input {
  width: 200px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
  transition: all 0.3s;
}

.chart-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.chart {
  width: 100%;
  height: 400px;
}

.chart-group {
  display: flex;
  margin-bottom: 20px;
}

.chart-group .chart-card {
  flex: 1;
  margin-right: 20px;
}

.chart-group .chart-card:last-child {
  margin-right: 0;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .time-selector {
    margin-top: 10px;
    width: 100%;
  }

  .input {
    width: 100%;
  }

  .chart-group {
    flex-direction: column;
  }

  .chart-group .chart-card {
    margin-right: 0;
    margin-bottom: 20px;
  }

  .chart-group .chart-card:last-child {
    margin-bottom: 0;
  }
}
</style>
<!-- <template>
  <div>
    <div style="margin: 20px 0">
      <el-select class="input" v-model="timeRange" placeholder="请选择" @change="load">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
    <el-card>
      <div id="line" style="width: 100%; height: 400px"></div>
    </el-card>
 
    <div style="margin: 20px 0">
      <el-select class="input" v-model="timeRange" placeholder="请选择" @change="load">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div style="display: flex;">
      <el-card style="flex: 1; margin-right: 20px;">
        <div id="pie" style="width: 100%; height: 400px"></div>
      </el-card>
      <el-card style="flex: 1;">
        <div id="line" style="width: 100%; height: 400px"></div>
      </el-card>
    </div>

  </div>


</template>

<script>
import Cookies from 'js-cookie'
import request from "@/utils/request";
import * as echarts from 'echarts'



const pieOption = {
  title: {
    text: '借书种类统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '借书种类',
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}

const option = {

  title: {
    text: '图书借还统计'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['借书数量', '还书数量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '借书数量',
      type: 'bar',
      stack: 'Total',
      smooth: true,
      data: []
    },
    {
      name: '还书数量',
      type: 'bar',
      stack: 'Total',
      smooth: true,
      data: []
    }
  ]
}

  export default {
    data() {
      return {
        admin: Cookies.get('admin') ? JSON.parse(Cookies.get('admin')) : {},
        lineBox: null,
        pieBox: null,
        timeRange: 'week',
        options: [
          {label: '最近一周', value: 'week'},
          {label: '最近一个月', value: 'month'},
          {label: '最近两个月', value: 'month2'},
          {label: '最近三个月', value: 'month3'},
        ]
      }
    },
    mounted() {
      this.load()
    },
    methods: {
      load() {
        if (!this.lineBox) {
          this.lineBox = echarts.init(document.getElementById('line'))
        }
        if (!this.pieBox) {
          this.pieBox = echarts.init(document.getElementById('pie'))
        }

        request.get('/borrow/lineCharts/' + this.timeRange).then(res => {
          option.xAxis.data = res.data.date
          option.series[0].data = res.data.borrow
          option.series[1].data = res.data.retur
          this.lineBox.setOption(option)
        })

        request.get('/borrow/pieCharts/' + this.timeRange).then(res => {
          pieOption.series[0].data = res.data.categories
          this.pieBox.setOption(pieOption)
        })
      }
    }
  }
</script>

<style>
.input {
  width: 300px;
}
</style> -->
